package com.laoli.lab39;

import java.util.concurrent.CompletableFuture;

/**
 * exceptionally()与handle()结合使用示例
 */
public class ExceptionallyAndHandle {
    public static void main(String[] args) throws InterruptedException {
        // 异步任务
        CompletableFuture<Object> task = CompletableFuture.supplyAsync(() -> {
                    //return new Random().nextInt(10) + 1;
                    throw new RuntimeException("taskAException");
                })
                .handle((result, exception) -> {
                    if(exception!=null){
                        System.out.printf("【handle】发生异常：%s \n", exception.getCause().getMessage());
                        throw new RuntimeException(exception.getCause().getMessage());//重新抛出异常给exceptionally处理
                    }
                    return result;
                })
                .exceptionally(exception -> {
                    System.out.printf("【exceptionally】发生异常：%s \n", exception.getCause().getMessage());
                    return 0;
                });
        // 主线程休眠
        Thread.sleep(5000);
    }
}
